package org.jeecg.modules.demo.houseOrder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.houseOrder.entity.Expense;
import org.jeecg.modules.demo.houseOrder.entity.FyCost;
import org.jeecg.modules.demo.houseOrder.entity.HouseOrder;
import org.jeecg.modules.demo.houseOrder.service.IExpenseService;
import org.jeecg.modules.demo.houseOrder.service.IFyCostService;
import org.jeecg.modules.demo.houseOrder.service.IHouseOrderService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 入库单
 * @Author: jeecg-boot
 * @Date:   2021-12-13
 * @Version: V1.0
 */
@Api(tags="入库单")
@RestController
@RequestMapping("/houseOrder/houseOrder")
@Slf4j
public class HouseOrderController extends JeecgController<HouseOrder, IHouseOrderService> {

	@Autowired
	private IHouseOrderService houseOrderService;

	@Autowired
	private IFyCostService fyCostService;

	@Autowired
	private IExpenseService expenseService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;

	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param houseOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "入库单-分页列表查询")
	@ApiOperation(value="入库单-分页列表查询", notes="入库单-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="yunxiao/houseOrder/HouseOrderList")
	public Result<?> queryPageList(HouseOrder houseOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HouseOrder> queryWrapper = QueryGenerator.initQueryWrapper(houseOrder, req.getParameterMap());
		queryWrapper.ne("RKLB",2);
		queryWrapper.ne("FYJE",0);
		Page<HouseOrder> page = new Page<HouseOrder>(pageNo, pageSize);
		IPage<HouseOrder> pageList = houseOrderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param houseOrder
     * @return
     */
    @AutoLog(value = "入库单-添加")
    @ApiOperation(value="入库单-添加", notes="入库单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HouseOrder houseOrder) {
        houseOrderService.save(houseOrder);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param houseOrder
     * @return
     */
    @AutoLog(value = "入库单-编辑")
    @ApiOperation(value="入库单-编辑", notes="入库单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HouseOrder houseOrder) {
        houseOrderService.updateById(houseOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "入库单-通过id删除")
    @ApiOperation(value="入库单-通过id删除", notes="入库单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        houseOrderService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "入库单-批量删除")
    @ApiOperation(value="入库单-批量删除", notes="入库单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.houseOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HouseOrder houseOrder) {
        return super.exportXls(request, houseOrder, HouseOrder.class, "入库单");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HouseOrder.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-费用单-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "费用单-通过主表ID查询")
	@ApiOperation(value="费用单-通过主表ID查询", notes="费用单-通过主表ID查询")
	@GetMapping(value = "/listFyCostByMainId")
    public Result<?> listFyCostByMainId(FyCost fyCost,
										@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
										@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
										HttpServletRequest req) {
        QueryWrapper<FyCost> queryWrapper = QueryGenerator.initQueryWrapper(fyCost, req.getParameterMap());
        Page<FyCost> page = new Page<FyCost>(pageNo, pageSize);
        IPage<FyCost> pageList = fyCostService.getListByOrder(page, fyCost);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param fyCost
	 * @return
	 */
	@AutoLog(value = "费用单-添加")
	@ApiOperation(value="费用单-添加", notes="费用单-添加")
	@PostMapping(value = "/addFyCost")
	public Result<?> addFyCost(@RequestBody FyCost fyCost) {
		fyCostService.save(fyCost);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param fyCost
	 * @return
	 */
	@AutoLog(value = "费用单-编辑")
	@ApiOperation(value="费用单-编辑", notes="费用单-编辑")
	@PutMapping(value = "/editFyCost")
	public Result<?> editFyCost(@RequestBody FyCost fyCost) {
		fyCostService.updateById(fyCost);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "费用单-通过id删除")
	@ApiOperation(value="费用单-通过id删除", notes="费用单-通过id删除")
	@DeleteMapping(value = "/deleteFyCost")
	public Result<?> deleteFyCost(@RequestParam(name="id",required=true) String id) {
		fyCostService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "费用单-批量删除")
	@ApiOperation(value="费用单-批量删除", notes="费用单-批量删除")
	@DeleteMapping(value = "/deleteBatchFyCost")
	public Result<?> deleteBatchFyCost(@RequestParam(name="ids",required=true) String ids) {
	    this.fyCostService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportFyCost")
    public ModelAndView exportFyCost(HttpServletRequest request, FyCost fyCost) {
		 // Step.1 组装查询条件
		 QueryWrapper<FyCost> queryWrapper = QueryGenerator.initQueryWrapper(fyCost, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<FyCost> pageList = fyCostService.list(queryWrapper);
		 List<FyCost> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "费用单"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, FyCost.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("费用单报表", "导出人:" + sysUser.getRealname(), "费用单"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importFyCost/{mainId}")
    public Result<?> importFyCost(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<FyCost> list = ExcelImportUtil.importExcel(file.getInputStream(), FyCost.class, params);
				 for (FyCost temp : list) {
                    temp.setWoNo(mainId);
				 }
				 long start = System.currentTimeMillis();
				 fyCostService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-费用单-end----------------------------------------------*/

    /*--------------------------------子表处理-费用分摊单-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "费用分摊单-通过主表ID查询")
	@ApiOperation(value="费用分摊单-通过主表ID查询", notes="费用分摊单-通过主表ID查询")
	@GetMapping(value = "/listExpenseByMainId")
    public Result<?> listExpenseByMainId(Expense expense,
													 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
													 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
													 HttpServletRequest req) {
        QueryWrapper<Expense> queryWrapper = QueryGenerator.initQueryWrapper(expense, req.getParameterMap());
        Page<Expense> page = new Page<Expense>(pageNo, pageSize);
        IPage<Expense> pageList = expenseService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param expense
	 * @return
	 */
	@AutoLog(value = "费用分摊单-添加")
	@ApiOperation(value="费用分摊单-添加", notes="费用分摊单-添加")
	@PostMapping(value = "/addExpense")
	public Result<?> addExpense(@RequestBody Expense expense) {
		expenseService.save(expense);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param expense
	 * @return
	 */
	@AutoLog(value = "费用分摊单-编辑")
	@ApiOperation(value="费用分摊单-编辑", notes="费用分摊单-编辑")
	@PutMapping(value = "/editExpense")
	public Result<?> editExpense(@RequestBody Expense expense) {
		expenseService.updateById(expense);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "费用分摊单-通过id删除")
	@ApiOperation(value="费用分摊单-通过id删除", notes="费用分摊单-通过id删除")
	@DeleteMapping(value = "/deleteExpense")
	public Result<?> deleteExpense(@RequestParam(name="id",required=true) String id) {
		expenseService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "费用分摊单-批量删除")
	@ApiOperation(value="费用分摊单-批量删除", notes="费用分摊单-批量删除")
	@DeleteMapping(value = "/deleteBatchExpense")
	public Result<?> deleteBatchExpense(@RequestParam(name="ids",required=true) String ids) {
	    this.expenseService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportExpense")
    public ModelAndView exportExpense(HttpServletRequest request, Expense expense) {
		 // Step.1 组装查询条件
		 QueryWrapper<Expense> queryWrapper = QueryGenerator.initQueryWrapper(expense, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<Expense> pageList = expenseService.list(queryWrapper);
		 List<Expense> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "费用分摊单"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, Expense.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("费用分摊单报表", "导出人:" + sysUser.getRealname(), "费用分摊单"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExpense/{mainId}")
    public Result<?> importExpense(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<Expense> list = ExcelImportUtil.importExcel(file.getInputStream(), Expense.class, params);
				 for (Expense temp : list) {
                    temp.setWoNo(mainId);
				 }
				 long start = System.currentTimeMillis();
				 expenseService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-费用分摊单-end----------------------------------------------*/




}
